import rules from './dict'

// NOT-NULL
const notNull = (str) => {
    if (str == ''  || str == undefined || str.length == 0) {
        return false;
    }
    return true;
}

// LENGTH_LIMIT
const lengthLimit = (str, maxLength, minLength = 0) => {
    if (str.length > maxLength) {
        return false;
    }
    if (str.length < minLength) {
        return false;
    }
    return true;
}

// PURE_LETTER
const pureLetter = (str) => {
    return /^[A-Za-z]+$/.test(str);
}

// NUMBER-LETTER
const numberLetter = (str) => {
    return /^[A-Za-z0-9]+$/.test(str);
}

// LIMIT-INPUT
const limitInput = (str, rule) => {
    const flag = rule.inputList.includes(str);
    if (!flag) {
        rule.help = '仅限输入 ' + rule.inputList.join(' or ');
    }
    return flag;
}

function verify (rule,str)  {
    switch (rule.type) {
        case rules.NOT_NULL: {
            return notNull(str);
        }
        case rules.LENGTH_LIMIT: {
            return lengthLimit(str,rule.maxLength,rule.minLength)
        }
        case rules.PURE_LETTER: {
            return pureLetter(str);
        }
        case rules.NUMBER_LETTER: {
            return numberLetter(str);
        }
        case rules.LIMIT_INPUT: {
            return limitInput(str,rule);
        }
        default: {
            return true;
        }
    }
}

function verifying (form,config,validate) {
    let result = true;

    for (let prop in config) {
        if (config[prop].rules == undefined) {
            continue;
        }
        const rules = config[prop].rules
        for (let index in rules) {
            let flag = verify(rules[index],form[prop]);
            if (!flag) {
                validate[prop] = {};
                validate[prop].pass = false;
                validate[prop].help = rules[index].help;
                result = false;
                break;
            } else {
                validate[prop] = {};
                validate[prop].pass = true;
                validate[prop].help = '';
            }
        }
    }
    return result;
}

export default verifying;